package com.example.arrange;

import com.example.util.CommonUtils;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ThenComposeDemo3 {
    public static void main(String[] args) {
        CommonUtils.printThreadLog("main start");

        String path = "filter_words.txt";

        ExecutorService executor = Executors.newFixedThreadPool(4);


        System.out.println("使用默认线程池");
        CompletableFuture<String[]> filterWordsFuture1 = readWordArrayFuture(path);
        System.out.println(Arrays.toString(filterWordsFuture1.join()));

        System.out.println("两个任务都使用自定义程池");
        CompletableFuture<String[]> filterWordsFuture2 = readWordArrayFuture(path, executor);
        System.out.println(Arrays.toString(filterWordsFuture2.join()));

        System.out.println("仅后一个任务使用自定义线程池");
        CompletableFuture<String[]> filterWordsFuture3 = CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        }).thenCompose(content -> CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("将内容转为字符串数组");
            return content.split(",");
        }, executor));
        System.out.println(Arrays.toString(filterWordsFuture3.join()));

        executor.shutdown();
        CommonUtils.printThreadLog("main end");
    }

    private static CompletableFuture<String> readFileFuture(String path) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        });
    }

    private static CompletableFuture<String> readFileFuture(String path, ExecutorService executor) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("读取文件：" + path);
            return CommonUtils.readFile(path);
        }, executor);
    }

    private static CompletableFuture<String[]> splitFuture(String content, ExecutorService executor) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("将内容转为字符串数组");
            return content.split(",");
        }, executor);
    }

    private static CompletableFuture<String[]> splitFuture(String content) {
        return CompletableFuture.supplyAsync(() -> {
            CommonUtils.printThreadLog("将内容转为字符串数组");
            return content.split(",");
        });
    }

    private static CompletableFuture<String[]> readWordArrayFuture(String path) {
        return readFileFuture(path).thenCompose(ThenComposeDemo3::splitFuture);
    }

    private static CompletableFuture<String[]> readWordArrayFuture(String path, ExecutorService executor) {
        return readFileFuture(path, executor).thenCompose(content -> splitFuture(content, executor));
    }
}
